package it.gat.client.view;

import it.gat.controller.TipologiaDispositivoController;
import it.gat.model.TipologiaDispositivo;

import java.awt.Container;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JInternalFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import javax.swing.table.DefaultTableModel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyVetoException;

public class TipologieSelectionFrame extends JInternalFrame {
	private JTable table;
	private List<TipologiaDispositivo> tipologie;
	private JInternalFrame thisFrame;
	/**
	 * Create the frame.
	 */
	public TipologieSelectionFrame(String title,final Container desktop,final ITipologieSelection frame) {
		super(title);
		this.setClosable(true);
		setBounds(0, 0, 600, 383);
		thisFrame=this;
		
		DefaultTableModel model = new DefaultTableModel(getDataTable(),getHeaderTable()){
		    @Override
		    public boolean isCellEditable(int row, int column) {
		       //all cells false
		       return false;
		    }
		};
	    table = new JTable(model);
	    table.addMouseListener(new MouseAdapter() {
	    	@Override
	    	public void mouseClicked(MouseEvent e) {
	    		if (e.getClickCount() == 2) {
	    	         JTable target = (JTable)e.getSource();
	    	         int row = target.getSelectedRow();
	    	         frame.setTipologiaSelection(tipologie.get(row));
	    	         try {
							thisFrame.setClosed(true);
						} catch (PropertyVetoException ex) {
							// TODO Auto-generated catch block
							ex.printStackTrace();
						}
	    		}}
	    });
	    
	    table.setRowSelectionInterval(0, 0);

	    JScrollPane scrollPane = new JScrollPane(table);
	    
	    getContentPane().add(scrollPane); 

	    setVisible(true);

	}
	
	private String[] getHeaderTable()
	{
		String[] columnName = {"Codice","Descrizione"};
		return columnName;
	}
	
	private String[][] getDataTable()
	{
		TipologiaDispositivoController cc = new TipologiaDispositivoController();
		tipologie = cc.getTipologiaDispositivoList();
		List<String[]> data = new ArrayList<String[]>();
		for(TipologiaDispositivo tipologia: tipologie){
				String[] tipologiaArray = {Integer.toString(tipologia.getIdTipologiaDispositivo()),
						                 tipologia.getDescrizione()};
				data.add(tipologiaArray);
			}
		return data.toArray(new String[0][0]);
	}
	
}
